package main.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by hdt3213 on 17/3/23.
 */

public class SingleTcpServer implements Runnable {

	private Socket client = null;
	private String address;
	private TcpApp app = null;

	public void setApp(TcpApp app) { this.app = app; }

	public SingleTcpServer(Socket client) {
		this.client = client;
	}

	@Override
	public void run() {
		try {
			String host = client.getInetAddress().toString();
			String port = Integer.toString(client.getPort());

			PrintStream out = new PrintStream(client.getOutputStream());
			System.out.println("Get Connection");
			BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));

			address = host + ":" + port;

			while (true) {

				String str = buf.readLine();
				if (str != null) {
					System.out.println("echo:" + str);
					out.println("echo:" + str);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		AtomicInteger numThreads = new AtomicInteger(0);
		ArrayList<Thread> list = new ArrayList<Thread>();

		try {
			ServerSocket socket = new ServerSocket(5000);

			while (true) {
				// accept a new connection
				Socket client = socket.accept();
				Thread thread = new Thread(new SingleTcpServer(client));
				list.add(thread);
				thread.start();
				numThreads.incrementAndGet();

			}
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

}
